import React, {useRef} from 'react';
import GoBack from "@/components/TheGoBack";
import {useLocation, useNavigate} from 'react-router-dom';
import {ProForm, ProFormDateTimeRangePicker, ProFormDigit, ProFormText} from '@ant-design/pro-components';
import {Col, message, Row, Space} from "antd";
import Goods from "../goods/index.jsx";
import moment from "moment";
import {apiPostSpellTogetherAdd, apiPostSpellTogetherEdit, apiGetSpellTogetherView} from '@/api/spellTogether/index.js';
import Decimal from "decimal.js";

const Add = () => {
    const location = useLocation();
    const navigate = useNavigate();
    const formRef = useRef();
    const format = "YYYY-MM-DD HH:mm";
    const mode = location.state.mode;
    const activityId = location.state.activityId;
    let title = null;

    switch (mode) {
        case 'add':
            title = "新建拼团活动";
            break;
        case 'edit':
            title = "编辑拼团活动";
            break;
        case 'view':
            title = "查看拼团活动";
            break;
        default:
            break;
    }
    // 将数据转成表格格式
    const convertData = (data) => {
        // console.log(data)
        return data.map((item, index) => {
            return {
                key: index,
                killSort: item.sort,
                goodsId: item.goodsId,
                goodsName: item.goodsName,
                skuInfoVos: item.skuList.map((sku, index) => {
                    return {
                        "materialId": sku.materialId,//物料编码
                        "goodsSkuId": sku.goodsSkuId,//skuId
                        skuAttributes: sku.skuAttributes || [],
                        skuStock: sku.skuStock,
                        "a_stock": sku.activityStock,//活动库存
                        skuCurrentPrice: sku.skuCurrentPrice,
                        "a_price": sku.activityGoodsSkuPrice ? Decimal(sku.activityGoodsSkuPrice ?? 0).div(Decimal(100)).toNumber() : 0,//活动价格
                        // 'isLimit': sku.quota === -1 ? 0 : 1,
                        // "quota_count": sku.quota !== -1 ? sku.quota : mode !== 'view' ? null : -1,
                        // "virtualCount": sku.virtualNum,//虚拟抢购件数
                        // goodsBuySum: sku.goodsBuySum,
                        // goodsSurplusSum: sku.goodsSurplusSum,
                        // "activityStock_copy": sku.activityStock
                    }
                })
            }
        })
    }
    const transData = (data) => {
        // console.log(data)
        return data.map(item => {
            return {
                "goodsId": item.goodsId,//商品id
                "goodsName": item.goodsName,//商品名称
                "goodsShowImages": item.goodsShowImages,
                "sort": item.killSort,//排序
                "skuList": item.skuInfoVos.map(sku => {
                    return {
                        "goodsSkuId": sku.goodsSkuId,//skuId
                        "skuAttributes": sku.skuAttributes,
                        "activityStock": sku.a_stock,//活动库存
                        "activityGoodsSkuPrice": sku.a_price ? sku.a_price * 100 : 0,//活动价格
                        "activityGoodsSkuOriginalPrice": sku.skuOriginalPrice,
                        "skuStock": sku.skuStock,//库存
                        "skuCurrentPrice": sku.skuCurrentPrice,//日常价格
                    }
                })
            }
        })
    }
    const setTData = (v) => {
        formRef.current.setFieldsValue({
            goodsList: transData(v)
        })
    }
    const formItemLayout = {
        labelCol: {span: 2},
        wrapperCol: {span: 22},
    }
    return (
        <div className={'wrap-box'}>
            <GoBack title={title}/>
            <div className={'wrap-box-content'}>
                <ProForm
                    {...formItemLayout}
                    formRef={formRef}
                    // readonly={mode==='view'}
                    layout={'horizontal'}
                    submitter={{
                        render: (props, doms) => {
                            return mode === 'view' ? null : <Row>
                                <Col span={22} offset={2}>
                                    <Space>{doms}</Space>
                                </Col>
                            </Row>
                        },
                    }}
                    // onValuesChange={(changeValues, all) => console.log(changeValues, all)}
                    onFinish={async (values) => {
                        delete values.temp
                        if (mode === 'add') {
                            await apiPostSpellTogetherAdd(values).then(res => {
                                if (res.code === 0 && res.data) {
                                    message.success('创建成功');
                                    navigate(-1)
                                }
                            })
                        } else {
                            await apiPostSpellTogetherEdit({...values, activityId}).then(res => {
                                if (res.code === 0 && res.data) {
                                    message.success('修改成功');
                                    navigate(-1)
                                }
                            })
                        }
                    }}
                    onFinishFailed={(values) => {
                        if (values.errorFields.length) {
                            message.error('请完善数据')
                        }
                    }}
                    params={{}}
                    request={async () => {
                        // 判断当前页面类型
                        if (mode !== 'add') {
                            // 跑接口取回显数据
                            let res = await apiGetSpellTogetherView({activityId})
                            if (res.code === 0) {
                                res.data.activityTime = [res.data.startTime, res.data.endTime];
                                return res.data
                            }
                        } else {
                            return {};
                        }
                    }}
                >
                    <ProFormText
                        width="md"
                        disabled={mode === 'view'}
                        name="activityName"
                        label="活动名称"
                        fieldProps={{
                            showCount: true,
                            maxLength: 50
                        }}
                        rules={[{required: true, message: '请输入活动名称'}]}
                    />
                    <ProFormDateTimeRangePicker
                        width="md"
                        name={'activityTime'}
                        label="活动时间"
                        showTime
                        disabled={mode === 'edit' || mode === 'view'}
                        fieldProps={{
                            // format: (value) => value.format(format),
                            format: "YYYY-MM-DD HH:mm"
                        }}
                        transform={(values) => {
                            return {
                                startTime: values ? values[0] : undefined,
                                endTime: values ? values[1] : undefined,
                            };
                        }}
                        rules={[
                            {
                                required: true,
                                validator: (_, value) => {
                                    if (value) {
                                        let a = moment(new Date()).format(format);
                                        let b = null;
                                        if (typeof value[1] === 'string' || value[1] instanceof String) {
                                            b = moment(value[1]).format('YYYY-MM-DD HH:mm');
                                        } else {
                                            b = value[1].format('YYYY-MM-DD HH:mm');
                                        }
                                        if (moment(a).isBefore(b)) {
                                            return Promise.resolve();
                                        }
                                        return Promise.reject(new Error('请选择未来的时间范围'));
                                    } else {
                                        return Promise.reject(new Error('请选择活动时间'));
                                    }
                                },
                            }
                        ]}
                    />
                    <ProFormDigit
                        width="md"
                        label="成团时间"
                        disabled={mode === 'edit' || mode === 'view'}
                        name="teamPeriod"
                        min={1}
                        max={72}
                        rules={[{required: true, message: '请填写不超过72的正整数'}]}
                        fieldProps={{
                            precision: 0,
                            addonBefore: '发起后',
                            addonAfter: '小时内有效',
                        }}
                    />
                    <ProFormDigit
                        width="md"
                        label="成团人数"
                        disabled={mode === 'edit' || mode === 'view'}
                        name="teamSize"
                        min={2}
                        max={99}
                        rules={[{required: true, message: '请填2~99之间的整数'}]}
                        fieldProps={{
                            precision: 0,
                            addonAfter: '人'
                        }}
                    />
                    <ProForm.Item
                        label="商品"
                        name="goodsList"
                        trigger="onValuesChange"
                        rules={
                            [
                                {
                                    required: true,
                                    message: ""
                                },
                                ({getFieldValue}) => ({
                                    validator(_, value) {
                                        if (value.length < 1) {
                                            return Promise.reject(new Error('请至少选择1个商品'));
                                        }
                                        return Promise.resolve();
                                    },
                                }),
                            ]
                        }
                        convertValue={(value) => {
                            if (value) {
                                return convertData(value)
                            } else return []
                        }}
                    >
                        <Goods mode={mode} set={setTData} activityId={activityId} formRef={formRef}/>
                    </ProForm.Item>
                </ProForm>
            </div>
        </div>
    )
};
export default Add;
